package per.yhh.xxxtsj.Handler;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import per.yhh.xxxtsj.Utils.JWTUtils;
import per.yhh.xxxtsj.entity.Message;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class OptionInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(OptionInterceptor.class);
    private static final HashMap<String, Integer> account2permission = new HashMap<>();
    @Autowired
    UserService userService;
    public Integer getPermission(String account) {
        return account2permission.get(account);
    }

    public void setPermission(String account) {
        User user = userService.getUserByAccount(account);
        account2permission.put(account, user.getPermissions());
    }

    private void responseUtil(HttpServletResponse response, Message msg) throws IOException {
        //重置response
        response.reset();
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(msg));
        pw.flush();
        pw.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //http的header中获得token
        String token = request.getHeader(JWTUtils.token);

        //token不存在
        if (token == null || token.equals("")) {
            responseUtil(response, Message.Unauthorized("token不存在"));
            return false;
        }
        ;
        //验证token
        String account = null;

        try {
            account = JWTUtils.validateToken(token);
            String requestURI = request.getRequestURI();
            if (checkPermission(response, account, requestURI)) return false;
        } catch (TokenExpiredException e) {
            responseUtil(response, Message.Unauthorized("未知错误"));
            return false;
        }
        if (account == null || account.equals("")) {
            responseUtil(response, Message.Unauthorized("未解析出token"));
            return false;
        }
        ;
        //更新token有效时间 (如果需要更新其实就是产生一个新的token)
        try {
            if (JWTUtils.isNeedUpdate(token)) {
                String newToken = JWTUtils.createToken(account);
                response.setHeader(JWTUtils.token, newToken);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private boolean checkPermission(HttpServletResponse response, String account, String requestURI) throws IOException {

        logger.info(requestURI);
        boolean b = requestURI.startsWith("/good")
                || requestURI.startsWith("/order")
                || requestURI.startsWith("/orderitem")
                || requestURI.startsWith("/categories")
                || requestURI.startsWith("/menus");
        logger.info(String.valueOf(b));
        if(b) return false;
        Integer permission = getPermission(account);
        setPermission(account);
        if (permission == null) {
            setPermission(account);
        }
        permission = getPermission(account);

        switch (permission) {
            case 0:
            case 1:
                break;
            case 2:
                if (requestURI.startsWith("/good/addgood")) {
                    break;
                }
                responseUtil(response, Message.InsufficientPermissions());
                return true;
            case 3:
                //普通用户可以访问商品和订单页面
                if (requestURI.startsWith("/good/addgood")) {
                    responseUtil(response, Message.InsufficientPermissions());
                    return true;
                }
                responseUtil(response, Message.InsufficientPermissions());
                return true;
        }
        return false;
    }
}